// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const TcbRouter = require('tcb-router')

const db = cloud.database()

const _ = db.command

const MAX_LIMIT = 100

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const _openid = wxContext.OPENID

  const app = new TcbRouter({
    event
  })
  // 会员状态、总积分
  app.router('integral', async (ctx, next) => {
    let integral = await db.collection('user').where({
      _id:_openid
    }).get().then((res) =>{
      return res.data
    })
    ctx.body = integral
  })
  // 积分明细
  app.router('integrallist', async (ctx, next) => {
    let integralList = await db.collection('integral').where({
      _openid:_openid
    }).skip(event.start).limit(event.count).orderBy("createTime", "desc").get().then((res) => {
        return res.data
      })
    ctx.body = integralList
  })
  //查询一个专题的属性
  app.router('onetopic', async (ctx, next) => {
    let list = await db.collection('topic').where({
      name: event.name
    }).get().then((res) => {
      return res.data
    })
    ctx.body = list
  })
  //分类查询blog
  app.router('topic', async (ctx, next) => {
    let list = await db.collection('blog').where({
      topic:event.name,
      state: true
    }).skip(event.start).limit(event.count).orderBy("createTime", "desc").get().then((res) => {
      return res.data
    })
    ctx.body = list
  })
  //是否浏览过需要积分的blog
  app.router('academic', async (ctx, next) => {
    let academiclist = await db.collection('academic').where({
      blogid:event.blogid,
      _openid
    }).get().then((res) =>{
      return res.data
    })
    ctx.body = academiclist
  })
  //blog详情查询
  app.router('detail', async (ctx, next) => {
    let blogId = event.blogId
    let detail = await db.collection('blog').where({
      _id: blogId
    }).get().then((res) => {
      return res.data
    })
    // 评论查询
    const countResult = await db.collection('blog-comment').count()
    const total = countResult.total
    let commentList = {
      data: []
    }
    if (total > 0) {
      const batchTimes = Math.ceil(total / MAX_LIMIT)
      const tasks = []
      for (let i = 0; i < batchTimes; i++) {
        let promise = db.collection('blog-comment').skip(i * MAX_LIMIT)
          .limit(MAX_LIMIT).where({
            postId:blogId
          }).orderBy('createTime', 'desc').get()
        tasks.push(promise)
      }
      if (tasks.length > 0) {
        commentList = (await Promise.all(tasks)).reduce((acc, cur) => {
          return {
            data: acc.data.concat(cur.data)
          }
        })
      }
    }
    ctx.body = {
      commentList,
      detail,
    }
  })
  //最新blog、热门blog
  app.router('postslist', async (ctx, next) => {
    const keyword = event.keyword
    let w = {
      state: true
    }
    if (keyword.trim() != '') {
      w = {
        state: true,
        content: new db.RegExp({
          regexp: keyword,
          options: 'i'
        })
      }
    }
    let list = await db.collection('blog').where(w).skip(event.start).limit(event.count)
    .orderBy(event.orderByname, "desc").get().then((res) => {
      return res.data
    })
    ctx.body = list
  })
  // 收藏
  app.router('addcollect', async (ctx, next) => {
    let addcollect = await db.collection('collect').add({
      data:{
        _openid,
        blogid:event.blogid,
        createTime: db.serverDate(), // 服务端的时间
      }
    }).then((res) => {
      return res.data
    })
    let updatecollect = await db.collection('blog').where({
      _id:event.blogid
    }).update({
      data: {
        collectNum:_.inc(1)
      }
    }).then((res) => {
      return res.data
    })
    ctx.body = {
      addcollect,
      updatecollect
    }
  })
  // 取消收藏
  app.router('delcollect', async (ctx, next) => {
    let delcollect = await db.collection('collect').where({
      _openid,
      blogid: event.blogid
    }).remove().then((res) => {
      return res.data
    })
    let updatecollect = await db.collection('blog').where({
      _id: event.blogid
    }).update({
      data: {
        collectNum: _.inc(-1)
      }
    }).then((res) => {
      return res.data
    })
    ctx.body = {
      delcollect,
      updatecollect
    }
  })

  // 点赞
  app.router('addzan', async (ctx, next) => {
    let addzan = await db.collection('zan').add({
      data: {
        _openid,
        blogid: event.blogid,
        createTime: db.serverDate(), // 服务端的时间
      }
    }).then((res) => {
      return res.data
    })
    let updatezan = await db.collection('blog').where({
      _id: event.blogid
    }).update({
      data: {
        likeNum: _.inc(1)
      }
    }).then((res) => {
      return res.data
    })
    ctx.body = {
      addzan,
      updatezan
    }
  })
  // 取消点赞
  app.router('delzan', async (ctx, next) => {
    let delzan = await db.collection('zan').where({
      _openid,
      blogid: event.blogid
    }).remove().then((res) => {
      return res.data
    })
    let updatezan= await db.collection('blog').where({
      _id: event.blogid
    }).update({
      data: {
        likeNum: _.inc(-1)
      }
    }).then((res) => {
      return res.data
    })
    ctx.body = {
      delzan,
      updatezan
    }
  })
  // 查询收藏/点赞状态
  app.router('collect', async (ctx, next) => {
    let collect = await db.collection('collect').where({
      _openid,
      blogid:event.blogid
    }).get().then((res) =>{
      return res.data
    })
    let zan = await db.collection('zan').where({
      _openid,
      blogid: event.blogid
    }).get().then((res) => {
      return res.data
    })
    ctx.body = {
      collect,
      zan
    }
  })
  //我的blog查询
  app.router('myblog', async (ctx, next) => {
    let list = await db.collection('blog').where({
      _openid,
      state: true
    }).skip(event.start).limit(event.count)
      .orderBy('createTime', "desc").get().then((res) => {
      return res.data
    })
    ctx.body = list
  })
  //我的收藏
  app.router('mycollect', async (ctx, next) => {
    let collect = await db.collection('collect').where({
      _openid
    }).skip(event.start).limit(event.count).orderBy('createTime', "desc").get().then((res) => {
      return res.data
      console.log(res.data)
      console.log('res.data')
    })
    let collectlist = {
      data: []
    }
    if (collect.length > 0){
      const tasks = []
      for (let i = 0; i < collect.length; i++) {
        let promise = db.collection('blog').where({
            _id:collect[i].blogid,
            state: true
          }).orderBy('createTime', 'desc').get()
        tasks.push(promise)
      }
      console.log(tasks.length)
      if (tasks.length > 0) {
        collectlist = (await Promise.all(tasks)).reduce((acc, cur) => {
          return {
            data: acc.data.concat(cur.data)
          }
        })
      }
    }
    ctx.body ={
      collect,
      collectlist
    } 
  })
  //我的点赞
  app.router('myzan', async (ctx, next) => {
    let zan = await db.collection('zan').where({
      _openid
    }).skip(event.start).limit(event.count).orderBy('createTime', "desc").get().then((res) => {
      return res.data
    })
    let zanlist = {
      data: []
    }
    
    if (zan.length > 0) {
      const tasks = []
      for (let i = 0; i < zan.length; i++) {
        let promise = db.collection('blog').where({
          _id: zan[i].blogid,
          state: true
        }).orderBy('createTime', 'desc').get()
        tasks.push(promise)
      }
      if (tasks.length > 0) {
        zanlist = (await Promise.all(tasks)).reduce((acc, cur) => {
          return {
            data: acc.data.concat(cur.data)
          }
        })
      }
    }
    ctx.body = {
      zan,
      zanlist
    }
  })
  
  // 我的订单查询
  app.router('ddlist', async (ctx, next) =>{
    let list = await db.collection('DingDan').where({
      _openid
    }).skip(event.start).limit(event.count)
      .orderBy('createTime', "desc").get().then((res) => {
        return res.data
      })
    ctx.body = list
  })

  // 更新礼品的货存
  app.router('upgift', async (ctx, next) =>{
    let uplist = await db.collection('gift').where({
      _id: event.giftid
    }).update({
      data: {
        number: _.inc(-1)
      }
    })
  })

  // 获取用户信息
  app.router('getuserinfo', async (ctx, next) => {
    let info = await db.collection('user').where({
      _id: event.userid
    }).get().then((res) =>{
      return res.data
    })
    ctx.body = info
  })

  //用户的博客
  app.router('userblog', async (ctx, next) => {
    let list = await db.collection('blog').where({
      _openid:event.userid,
      state: true
    }).skip(event.start).limit(event.count)
      .orderBy('createTime', "desc").get().then((res) => {
        return res.data
      })
    ctx.body = list
  })

  //更新签到天数
  app.router('updateuserinfo', async (ctx, next) => {
    let list = await db.collection('user').where({
      _id: event.openid
    }).update({
      data:{
        tnum: _.inc(1)
      }
    })
  })

  //删除我的blog
  app.router('delblog', async (ctx, next) => {
    console.log(event.delid)
    console.log(1111111)
    let delblog = await db.collection('blog').where({
      _id: event.delid
    }).remove().then((res) =>{
      return res.data
    })
  })

  // 删除blog的评论
  app.router('delcomment', async (ctx, next) => {
    let delcomment = await db.collection('blog-comment').where({
      postId: event.blogId
    }).remove().then((res)=>{
      return res.data
    })
  })

  return app.serve()
}